package com.mccken.designpattern.strategy.strategy_04;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.tools.hat.internal.util.Comparer;

/**
 * 相当于项目经理角色
 *
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2024-01-14 21:51
 **/
public class DispatcherServlet extends HttpServlet {

	private List<Handler> handlerMapping = new ArrayList<Handler>();

	public void init() throws ServletException {
		try {
			Class<?> memberControllerClass = MemberController.class;
			handlerMapping.add(Handler.builder()
					.controller(memberControllerClass.newInstance())
					.method(memberControllerClass.getMethod("getMemberById", new Class[]{String.class}))
					.url("/web/getMemberById.json")
					.build());

		} catch (Exception e) {
		}
	}
	
	private void doDispatch(HttpServletRequest request, HttpServletResponse response) {
		// 1. 获取用户请求URL
		String uri = request.getRequestURI();
		
		// 2. Servlet获得URL之后，要做权衡（判断、选择）
		// 根据用户请求的URL，找到这个URL对应的某一个JAVA类的方法
		
		// 3. 通过获得的URL在handlerMapping中找到对应的Handler
		Handler handler = null;
		for (Handler h : handlerMapping) {
			if (uri.equals(h.getUrl())) {
				handler = h;
				break;
			}
		}
		
		// 4. 将具体的任务分发给Method
		Object obj = null;
		try {
			obj = handler.getMethod().invoke(handler.getController(), request.getParameter("mid"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 5. 获取Method执行结果，通过Response返回出去
		try {
			response.getWriter().write(String.valueOf(obj));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
